news.admin = liwe.module ( 'news.admin', null, "News" );

news.admin._cur_nid = null;
news.admin.tabs = null;
news.admin.admin_man = null;
news.admin._categs = null;
news.admin._dest_div = "news_content";//block_main";
news.admin._cur_id_parent = 0;
news.admin._cur_id_parent_name = '';
news.admin.has_dashboard = true;

news.admin._cat_params = {
	'color' : '#000000',
	'ico' : '',
	'visible' : 0
};

//{{{news.admin.cbacks = {
news.admin.cbacks = {
	"edit-inited" : null,		// chiamata quando il form e' pronto per l'editing
	"edit-custom-form" : null, 	// chiamata quando il form e' pronto, vuole un form come oggetto di ritorno    custom_form ( vals ) -> form
	"edit-save"   : null,   	// chiamata quando l'utente preme Salva (ma prima dell'AJAX)
	"tags-update" : null,		// chiamata quando l'utente aggiorna le news
	"set-categ" : null,
	
	"NULL" : null			// Cosi' possiamo dimenticarci le virgole in fondo
};
//}}}
//{{{news.admin._init_admin = function ( dest_div )
news.admin._init_admin = function ( dest_div )
{
	var _acts = [
			{ func: function () { news.admin.set (); }, label: 'Nuova News', 'default': true },
			{ func: function () { news.admin.list (); }, label: 'Elenco News', "class" : "news_list" },
			{ func: function () { news.admin.category (); }, label: 'Categorie', "class" : "category" }
		];

	news.admin.register ( _acts );
	news.admin._admin_manager_init ( dest_div );
	news.admin._am_cat_init ( 'category_list' );
	news.admin._am_sub_category_init ( 'category_workspace' ); 
};
//}}}
//{{{news.admin.get_dashboard = function ( cback )
news.admin.get_dashboard = function ( cback )
{
	//cback ( "sono le <b>news!</b>" );
	news.admin.ajax ( { action: 'news.ajax.list' }, function ( res )
	{
		if ( ! res.get ( 'news' ) )
		{
			cback ( 'Nessuna news inserita.' );
			return;
		}
		var html = new String.buffer ();
		res.news.iterate ( function ( n )
		{
			html.add ( String.formatDict ( news.templates [ 'dashboard' ], n ) );
		} );
		cback ( html.toString () );
	} );
};
//}}}
//{{{news.admin._render_layout = function ( panel, title )
news.admin._render_layout = function ( panel, title )
{
	var dct = { '_panel' : news.templates [ panel ], '_title' : title };
	$( 'system-content'  , String.formatDict ( news.templates [ 'NEWS_ADMIN_LAYOUT' ], dct ) );
};
//}}}
//{{{news.admin._set_add_info = function ( f, data )
news.admin._set_add_info = function ( f, data )
{
	if ( data )
	{
		try
		{
			eval ( 'news.admin._cat_params = ' + data [ 'params' ] );
		
		}catch ( err ){
		};
	};	
	f.set_value ( 'color' , news.admin._cat_params [ 'color' ] );
	f.set_value ( 'visible' , news.admin._cat_params [ 'visible' ] );
	
	$( 'cat_img_ws', '' );
	var _ws = $ ( 'cat_img_ws' );
	var _btn_add = document.createElement ( 'span' );
	_btn_add.className = 'button blue';
	_btn_add.innerHTML = 'Seleziona';
	liwe.events.add ( _btn_add , 'click', function ( ev ) { news.admin._display_dlm ( ev, f );} );	

	if ( ! news.admin._cat_params [ 'ico' ] )
	{
		var _label = document.createElement ( 'span' );
		_label.className = 'form_label fl';
		_label.innerHTML = 'Immagine non presente';
		_ws.appendChild ( _label );
		_ws.appendChild ( _btn_add );
	}else
	{
		//cambia immagine
		var _img = document.createElement ( 'img' );
		_img.src = news.admin._cat_params [ 'ico' ];
		_img.maxWidth = '200';
		_img.className = "form_img fl";
		_ws.appendChild ( _img );
		var _btn_clear =  document.createElement ( 'span' );
		_btn_clear.className = 'button grey';
		_btn_clear.innerHTML = 'Pulisci'
		_ws.appendChild ( _btn_add );
		_ws.appendChild ( _btn_clear );
		liwe.events.add ( _btn_clear , 'click', function ( ev ) 
		{ 
			news.admin._cat_params [ 'ico' ]  = '';
			news.admin._set_add_info ( f );
		} );	
		var _clear = document.createElement ( 'div');
		_clear.className = 'fc';
		_ws.appendChild ( _clear );
	};		

};
//}}}
//{{{news.admin._display_dlm = function ( ev, f )
news.admin._display_dlm = function ( ev, f )
{
	liwe.lightbox.fade = false;
	liwe.lightbox.easy ( "news_cat_img", "Inserimento immagine", 850, 660 );
	download_manager.cbacks [ 'image_click' ] = function ( url )
	{
		news.admin._cat_params [ 'ico' ] = url;
		liwe.lightbox.close ();
		news.admin._set_add_info ( f );
		return false;
	};
	download_manager.render ( "news_cat_img" );

}
//}}}
//{{{news.admin._admin_manager_init = function ( dest_div )
news.admin._admin_manager_init = function ( dest_div )
{
	if ( ! news.admin.admin_man )
	{
		news.admin.admin_man = new AdminManager ( { 
			'dest_res': dest_div,
			'list_action': "news.admin.list",
			'del_action': 'news.admin.delete' ,
			'mod_menu_actions': [
					{ func: "news.admin.set()", 'class' : 'add_16', label: 'Nuova News' }
				],
			'filter_form' : news.admin._filter_form,
			'filter_form_name' : "news-admin-filter",
			'edit_on_dbclick' : true,
			'generate_id' : function ( ds, row ) { return row [ 'id' ]; }
		} );

		news.admin.admin_man.set_row_fields ( 
					[
						[ "ID", "id" ],
						[ "Categoria", "categ" ],
						[ "Titolo / abstract", "_txt" ],
						[ "Data pubbl.", "_created" ],
						[ "Pos.", "pos" ]
					]
					);


		// news.admin.admin_man.templates ['table_start' ] = news.admin.templates [ 'table_start' ];
		// news.admin.admin_man.templates [ 'table_row' ] = news.admin.templates [ 'table_row' ];

		news.admin.admin_man.cbacks [ 'row_manip' ] = news.admin.list_row_manip;
		news.admin.admin_man.cbacks [ 'edit_item' ] = function ( id ) { news.admin.edit ( dest_div, id ); };
		news.admin.admin_man.cbacks [ 'del_item' ] = function ( id ) { news.admin.del ( dest_div, id ); };
		news.admin.admin_man.cbacks [ 'position' ] = news.admin.update_pos; 
		//ds_filter cback parameters:  { col name : { [ form ( func ) ], [ field ], [ cback function ] } }
		//news.admin.admin_man.cbacks [ 'ds_filter' ][ '_txt' ] = { field: 'title' };
		//ds_sort cback parameters:  { col name : { [ field ], [ cback function ] } }
		news.admin.admin_man.cbacks [ 'ds_sort' ][ 'id' ] = {};
		news.admin.admin_man.cbacks [ 'ds_sort' ][ 'pos' ] = {};
		news.admin.admin_man.cbacks [ 'ds_sort' ][ '_created' ] = { field: 'pub_date' };
	}
};
//}}}
//{{{news.admin._filter_form = function ( dest_div )
news.admin._filter_form = function ( dest_div )
{
	news.admin._create_categs ( function () 
		{
			var f = new liwe.form.instance ( "news-admin-filter" );

			f.hidden ( { name: 'ds_sort', value: '' } );
			f.hidden ( { name: 'ds_cond', value: '' } );
			f.select ( { label: 'Categoria', name: 'id_categs', options: news.admin._categs, nonl: true } );
			f.checkbox ( { name: 'visible', label: 'Visibile', value: 1, checked: "checked" } );
			f.text ( { label: "Titolo", name: "title", size: 24, maxlength: 140 } );
			f.text ( { label: "Testo", name: "testo", size: 24, maxlength: 140 } );
			f.calendar ( { name: 'pub_date_start', label: 'Data pubb. inizio', nonl: true } );
			f.calendar ( { name: 'pub_date_end', label: 'fine' } );
			f.tags ( { label: 'Tags', name: 'tags', module_name: "news" } );
			f.button ( { value: "Applica Filtro", "class": 'green',  onclick: "news.admin._filter_apply()", nonl: true } );
			f.button ( { value: "Svuota", "class" : "yellow",  onclick: "news.admin.list()" } );

			f.set ( dest_div );
		} );
};
//}}}
//{{{news.admin._filter_apply = function ()
news.admin._filter_apply = function ()
{
	news.admin.admin_man.search_start ();
};
//}}}
//{{{news.admin.list_row_manip = function ( ds, row )
news.admin.list_row_manip = function ( ds, row )
{
	row [ '_id' ] = row [ 'id' ];
	row [ '_txt' ] = '<b>' + row [ 'title' ] + '</b><br/> ' + row [ 'abstract' ];
	row [ '_id_categ' ] = row [ 'id_categ' ]; // for position

	row [ '_created' ] = '';
	if ( row.get ( 'pub_date' ) )
		row [ '_created' ] = liwe.utils.date2str ( row [ 'pub_date' ], 1 );

	if ( row.get ( '_img' ) )
		row [ '_txt' ] = String.formatDict ( news.templates [ 'admin_txt_row' ], row );
};
//}}}
//{{{news.admin.list = function ( dest_div )
news.admin.list = function ( dest_div )
{
	if ( dest_div ) news.admin._dest_div = dest_div;
	dest_div = news.admin._dest_div;
	news.admin._render_layout ( 'NEWS_CONTENT', 'Elenco News' ); 
	news.admin.admin_man.show_list ( dest_div );
};
//}}}
//{{{news.admin.update_pos = function ( id_news, id_categ, pos )
news.admin.update_pos = function ( id_news, id_categ, pos )
{
	var vals = {
			'action' : 'news.admin.update_pos',
			'id_news' : id_news,
			'id_categ' : id_categ,
			'pos' : pos
	}
	news.admin.ajax ( vals, function ( data )
				{
					news.admin._filter_apply ();
				} );
};
//}}}
//{{{news.admin.set = function ( dest_div, news_data )
news.admin.set = function ( dest_div, news_data )
{
	news.admin._render_layout ( 'NEWS_CONTENT', 'Inserimento/Modifica News' );

	if ( dest_div ) news.admin._dest_div = dest_div;
	dest_div = news.admin._dest_div;

	news.admin._init_tabs ( dest_div );

	if ( ! news_data ) news_data = {};

	news.admin._cur_nid = news_data.get ( "id", 0 );

	//news.admin._create_frm ( "news_form", news_data );
	news.admin._create_frm ( "news_form", news_data,
		function ()
		{
			// FIXME: passare anche "media_data"
			media_manager.admin.render ( "news_media", "news", news_data.get ( "id" ) );

			news.admin.tabs.render ();
			news.admin.tabs.send_event ( 'news_form', 'click' );

			news.admin.tabs.enable_tab ( "news_media", news_data.get ( "id" ) );

			if ( news.admin.cbacks [ 'edit-custom-form' ] ) 
			{
				var f = news.admin.cbacks [ 'edit-custom-form' ] ( news_data );
				f.set ( 'form-edit-custom-fields' );
			}

			news.admin._set_frm ( news_data );

			if ( news.admin.cbacks [ 'edit-inited' ] ) news.admin.cbacks [ 'edit-inited' ] ( news_data );
		} );
};
//}}}
//{{{news.admin.edit = function ( dest_div, id_news )
news.admin.edit = function ( dest_div, id_news )
{
	//news.get ( id_news, null, function ( v ) {
	liwe.AJAX.easy ( { action: "news.admin.get", 'id_news': id_news }, function ( v ) {
		news.admin.set ( dest_div, v.get ( 'news' ) );
	} );
};
//}}}
//{{{news.admin._set_frm = function ( news_data )
news.admin._set_frm = function ( news_data )
{
	if (  news_data.count() == 0 ) return;
	var f = liwe.form.get ( "news-set" );

	var set_vals =  [ 'id_abstract', 'id_descr', 'id_media', 'title', 'subtitle', 'id_categ', 'pub_date', 'abstract', 'tags', 'descr' ];

	news_data [ 'tags' ] = tags.convert ( news_data.get ( "tags" ) );

	set_vals.iterate ( function ( val )
	{
		f.set_value ( val, news_data [ val ] );		
	});

	f.set_value ( "id_news", news_data.get ( "id", 0 ) );
	var vis = news_data.get ( "visible", -1 );

	if ( vis == -1 || vis == 1) vis = true;
	else vis = false;
	f.set_value ( "visible", vis );

	if (! news_data [ 'fb' ] ) return;
	var fb_data = news_data [ 'fb' ];

	news.admin._social_fb_setlnk ( f, fb_data );
	
}
//}}}
//{{{news.admin._social_fb_setlnk = function ( form, fb_data )
news.admin._social_fb_setlnk = function ( form, fb_data )
{
	if ( fb_data [ 'post_id' ] == '' ) return;
	var _fb_chk = form.get_element ( 'facebook' ).parentNode;
	var _fb_lnk = document.createElement ( 'a' );
	_fb_lnk.href = 'http://www.facebook.com/' + fb_data [ 'post_id' ] .replace ( '_', '/posts/' );
	_fb_lnk.innerHTML = "Vai al Post";
	_fb_lnk.target = 'blank';
	_fb_chk.innerHTML = '';
	_fb_chk.setAttribute ( 'valign', 'center' );
	_fb_chk.appendChild ( _fb_lnk );
}
//}}}
//{{{news.admin._create_frm = function ( dest_div, news_data, cback )
news.admin._create_frm = function ( dest_div, news_data, cback )
{
	news.admin._create_categs ( function ()
		{
			var f = new liwe.form.instance ( "news-set" );

			/*
			var d = new Date ();
			var pub_date = news_data.get ( 'pub_date' );
			if ( ! pub_date ) pub_date = "";

			var taglist = tags.convert ( news_data.get ( "tags" ) );

			var vis = news_data.get ( "visible", -1 );

			if ( vis == -1 || vis == 1) vis = true;
			else vis = false;

			var now = new Date ();
			var time = String.format ( "%2.2d:%2.2d", parseInt ( now.getHours() ), parseInt ( now.getMinutes() ) );
			*/
			
			f.hidden ( 'id_news',  0  );
			f.hidden ( 'id_abstract',  0  );
			f.hidden ( 'id_descr',  0  );
			f.hidden ( 'id_media',  0  );
			f.hidden ( "action", "news.admin.create" );

			f.text ( { label: 'Titolo', name: "title", size: 24, maxlength: 140, value: "", mandatory: true, nonl: true } );
			f.text ( { label: 'Sottotitolo', name: "subtitle", size: 24, maxlength: 140, value: "", mandatory: true, nonl: true } );

			if ( typeof ( social ) != 'undefined' )
			{
				f.checkbox ( { label: '<span class="facebook-label">&nbsp;</span>', name: 'facebook', checked: false, value: 1 } );
			}
			else
			{
				f.label ( { value : ''} );
			}
			
			f.select ( { label: 'Categoria', name: 'id_categ', value: '' , options: news.admin._categs, mandatory: true, nonl: true } );
			f.calendar ( { label: 'Data pubblicazione', name: 'pub_date', time: true, nonl: true } );
			f.checkbox ( { label: 'Visibile', name: 'visible', checked : true,  value : 1 } );

			f.jconed ( { label: 'Descrizione Breve', name: "abstract",  width: 400, height: 200, value: "", nonl: true } );
			f.tags ( { label: 'Tags', name: 'tags',  module_name: "news",  rowspan: 2, 'event-update' : news.admin.cbacks [ 'tags-update' ] } );
						
			f.jconed ( { label: 'Testo', name: "descr", width: 400, height: 200, value: "", nonl: true } );
			f.label ( { value: '<div id="form-edit-custom-fields"></div>' } );

			f.sep ();
			f.button ( { name:'btn_save', "class": 'green', onclick: 'news.admin._set_click(\'' + dest_div + '\')', value: 'SALVA' } );

			f.set ( dest_div );

			if ( cback ) cback ();
		} );
};
//}}}
//{{{news.admin._init_tabs = function ( dest_div )
news.admin._init_tabs = function ( dest_div )
{
	var s = new String.buffer ();
	var res;

	if ( ! news.admin.tabs ) news.admin.tabs = new OS3Tabs.instance ( 'news-tabs' );

	news.admin.tabs.clear ();

	s.add ( news.templates [ 'env_start' ] );
	s.add ( news.templates [ 'tabs_start' ] );

	s.add ( String.formatDict ( news.templates [ 'tabs_tab' ], { "tab_name" : "news_form" } ) );
	news.admin.tabs.add ( 'News', 'news_form' );

	s.add ( String.formatDict ( news.templates [ 'tabs_tab' ], { "tab_name" : "news_media" } ) );
	news.admin.tabs.add ( 'Media', 'news_media' );

	s.add ( news.templates [ 'tabs_end' ] ); 
	s.add ( news.templates [ 'env_end' ] );

	res = s.toString ();

	$( dest_div, res );
};
//}}}
//{{{news.admin._set_click = function ( dest_div )
news.admin._set_click = function ( dest_div )
{
	var f = liwe.form.get ( "news-set" );
	var dct = f.get_values ();

	if ( ! f.check () )
	{
		system.admin.do_alert ( 'News: inserire tutti i valori richiesti', liwe.utils.notifier.mode.WARN );
		return;
	}

	
	if ( news.admin.cbacks [ 'edit-save' ] ) 
	{
		var check = news.admin.cbacks [ 'edit-save' ] ();
		if ( !check ) return;
		
	}
	liwe.AJAX.easy ( dct, function ( resp ) 
	{
		resp =  resp [ 'news' ];
		
		system.admin.do_alert ( "News salvata correttamente", liwe.utils.notifier.mode.NOTICE );
		

		liwe.lightbox.create ( 'news_message', 250, 5  );
		//contenuto
		var _box = $el ( 'news_message' );
		var _title = document.createElement ( 'h4');
		_title.className = "seph_e";
		_title.innerHTML = "News Salvata";
		_box.appendChild ( _title );
		
		var _btn_media = document.createElement ( 'div' )
		_btn_media.id = "news_message_btn_media";
		_btn_media.className = "button blue";
		_btn_media.innerHTML = "Aggiungi Immagini";
		liwe.events.add ( _btn_media , 'click', function () 
		{ 
			f.set_value ( "id_news", resp [ 'id_news' ] );
			fb_resp = resp [ 'fb' ]
			if ( fb_resp [ 'status' ] == 'OK'  )
			{
				news.admin._social_fb_setlnk ( f, fb_resp );
			};
			media_manager.admin.set_id_obj ( 'news', resp [ 'id_news' ] );
			news.admin.tabs.enable_tab ( "news_media", 1 );
			news.admin.tabs.send_event ( 'news_media', 'click' );
			liwe.lightbox.close()
		} );
		_box.appendChild ( _btn_media );
		
		var _btn_new = document.createElement ( 'div' );
		_btn_new.id = "news_message_btn_new";
		_btn_new.className = "btn_new button grey";
		_btn_new.innerHTML = "Nuova News";
		liwe.events.add ( _btn_new , 'click', function ()
		{
			news.admin.set ()		
			liwe.lightbox.close()
		});

		_box.appendChild ( _btn_new );
		
		liwe.fx.set_opacity ( _box , 0 );
		liwe.lightbox.show ();
		
		liwe.fx.fade_in ( _box, null, 2000 );
		
	} );
};
//}}}
//{{{news.admin.del = function ( dest_div, id_news )
news.admin.del = function ( dest_div, id_news )
{
	if ( ! id_news ) return;

	if ( confirm ( "Sei sicuro di voler eliminare questa news?" ) )
	{
		liwe.AJAX.easy ( { 'ids': id_news, 'action': "news.admin.delete" }, function ( v ) {
			news.admin.list ( dest_div );
		} );
	}
};
//}}}
// {{{ Gestione Categorie/Sottocategorie
// Show Category Panel
news.admin.category = function ( dest_div )
{
	news.admin._render_layout ( 'NEWS_ADMIN_CATEGORY', 'Gestione Categorie - Sottocategorie' ); 
	news.admin._am_category.show_list ( dest_div );
	news.admin.add_category();
};
//{{{news.admin._am_cat_init = function ( dest_div )
news.admin._am_cat_init = function ( dest_div )
{
	if ( news.admin._am_category ) return;
	news.admin._am_category = new AdminManager
							( {
									'dest_res'    : dest_div,
									'name'		: 'news_category',
									'list_action' : 'news.admin.list_am_categories',
									'edit_action' : 'news.admin.edit_category',
									'del_action' : 'news.admin.del_category',
									'mod_menu_actions': 
									[
										{ func: "news.admin.add_category()", 'class' : 'folder_open_add' , label: 'Nuova Categoria' }
									]
							} );


	news.admin._am_category.set_row_fields (
							[
									[ "Nome", "text" ]
							]
							);

	news.admin._am_category.set_row_actions ( 
						[ 
							[ news.templates [ 'sub_category_action' ], "sub_category" ]
						] );

	news.admin._am_category.cbacks [ 'row_manip' ] = news.admin._rwman_category;
	news.admin._am_category.cbacks [ 'edit_item' ] = function ( id ) { news.admin.edit_category ( id ); };
	news.admin._am_category.cbacks [ 'del_item' ] = function ( id ) { news.admin.del_category ( id ); };
	news.admin._am_category.cbacks [ 'sub_category' ] = function ( id ) { news.admin.show_sub_category ( id ); };
	news.admin._am_category.cbacks [ 'pre_del' ] = news.admin._cat_pre_del;

	news.admin._am_category.templates [ 'module_single_action' ] = news.templates [ 'module_single_action' ];
	news.admin._am_category.templates [ 'actions_row_action' ] = news.templates [ 'category_actions_row_action' ];
};
//}}}
//{{{news.admin._rwman_category = function ( ds, row )
news.admin._rwman_category = function ( ds, row )
{
	row [ '_id' ] = row [ 'id' ];
};
//}}}
// {{{ Category FORM ADD EDIT DELETE

news.admin._cat_pre_del = function ( am )
{
	var ids = am.get_selected ();
	if ( ids == -1 ) return true; 
	ids = "|".join ( ids )
	news.admin.del_category ( ids )	
	return false;
};

news.admin._category_form = function ()
{
        var f = new liwe.form.instance ( 'category_add' );
        f.hidden ( 'id' , '0' );
        f.hidden ( 'id_node' , news.admin._cur_id_parent );
        f.hidden ( 'id_parent' , '0' );
        f.text ( { 'name' : 'text', 'size' : 20, 'maxlength' : 50, 'mandatory' : true, 'label' : 'Categoria' } );
        f.text ( { 'name' : 'color', 'size' : 10, 'maxlength' : 7, 'mandatory' : true, 
		'label' : 'Colore', 'onclick': 'ColorPicker.show(this)'	} );
	f.checkbox ( { label: 'Visibile', name: 'visible', checked : false,  value : 1 } );
	f.label ( { 'label' : 'Immagine', value : "<div id='cat_img_ws'></div>" } );	
        f.button ( { value: 'Salva', "class": 'green', onclick : "news.admin._save_category()" } );
        f.set ( 'category_workspace' );
};

news.admin.add_category = function ( dest )
{
	$ ( 'title-work', 'Nuova Categoria' ); 
	news.admin._category_form();
        var f = liwe.form.get ( 'category_add' );
	news.admin._cat_params = {
		'color' : '#000000',
		'ico' : '',
		'visible' : 0
	};
	news.admin._set_add_info ( f );
	$( 'sub_category', '' );
};

news.admin.edit_category = function ( id_category )
{
	$ ( 'title-work', 'Modifica Categoria' ); 
	news.admin._cur_id_parent = id_category ;
	news.admin._category_form();
	var v = { action : 'news.ajax.get_categ', id_categ : id_category };
	news.ajax ( v , function ( data )
        {
		var categ = data [  'categ' ];
		news.admin._cur_id_parent = categ [ 'id' ];
		news.admin._cur_id_parent_name = categ [ 'text' ];
                var f = liwe.form.get ( 'category_add' );
                categ.iterate ( function ( val, k )
                {
                        f.set_value ( k, val );
                });
		news.admin._set_add_info ( f, categ );
	
        });
};


news.admin.del_category = function ( id_category, is_sub_category )
{
	
	var cback = news.admin.category;
	var msg = 'Categoria Eliminata';
	if ( is_sub_category ) 
	{
		cback =  function () { news.admin.show_sub_category ( news.admin._cur_id_parent );} ;
		msg = 'Sottocategoria Eliminata';
		
	};
	var v = { action : 'news.admin.del_categ', id_categ : id_category };
	news.admin.ajax ( v , function ( data )
        {
		system.admin.do_alert ( msg, liwe.utils.notifier.mode.NOTICE );
		cback();
	},
	function ( txt, err_descr, err_code, data )
	{
		if ( ! err_descr ) err_descr = txt;
		system.admin.do_alert ( err_descr, liwe.utils.notifier.mode.ALERT );
	});
};

news.admin._save_category = function ( is_sub_category )
{
	
	var f_name = 'category_add';
	var cback = news.admin.category;
	var msg = 'Categoria Salvata';
	var id_node = news.admin._cur_id_parent;
	news.admin._cur_id_parent = 0;
	if ( is_sub_category ) 
	{
		f_name = 'sub_category_add';
		cback =  function () { news.admin.show_sub_category ( id_node );} ;
		msg = 'Sottocategoria Salvata';
		news.admin._cur_id_parent = id_node;
	};

	
	var f = liwe.form.get ( f_name );
	if ( ! f.check () )
	{
		system.admin.do_alert ( 'Inserire titti i valori', liwe.utils.notifier.mode.WARN );
		return;
	}

	var dct = f.get_values ();

	news.admin._cat_params [ 'color' ] = f.get_value ( 'color' );	
	news.admin._cat_params [ 'visible' ] = f.get_value ( 'visible' );	

	if ( news.admin._cat_params [ 'visible' ] == false ) news.admin._cat_params [ 'visible' ] = 0; 

	dct [ 'params' ] =  news.admin._cat_params.toJSONString();

	dct [ 'action' ] = "news.admin.set_categ";

	liwe.AJAX.easy ( dct, function ( v ) {
		system.admin.do_alert ( msg, liwe.utils.notifier.mode.NOTICE );
		news.admin._cat_params = {
			'color' : '#000000',
			'ico' : '',
			'visible' : 0
		};
		cback();
	} );
};

// }}}
// {{{ Admin Manager Sub_Category

news.admin._am_sub_category_init = function ( dest_div )
{
        if ( news.admin._am_sub_category ) return;
        news.admin._am_sub_category = new AdminManager
                                ( {
                                        'dest_res'    : dest_div,
					'name'	      : 'news_sub_catagory',
                                        'list_action' : 'news.admin.list_am_sub_categories',
                                        'edit_action' : 'news.admin.edit_sub_category',
                                        'del_action' : 'news.admin.del_category',
                                        'mod_menu_actions': [
								 { func: "news.admin.add_sub_category()", 'class' : 'sub_folder_add' , label: 'Nuova Sottocategoria' }
							],

	                                'filter_form' : news.admin._am_sub_category_filter_form,
                                        'filter_form_name' : "sub_category_list_filter"
                                } );

	news.admin._am_sub_category.set_row_fields (
                                [
                                        [ "Nome", "text" ]
                                ]
                                );

        news.admin._am_sub_category.cbacks [ 'row_manip' ] = news.admin._rwman_sub_category;
        news.admin._am_sub_category.cbacks [ 'edit_item' ] = function ( id ) { news.admin.edit_sub_category ( id ); };
        news.admin._am_sub_category.cbacks [ 'del_item' ] = function ( id ) { news.admin.del_category ( id, true  ); };
	news.admin._am_sub_category.cbacks [ 'noresult' ] = function () { news.admin.add_sub_category (); };
        news.admin._am_sub_category.cbacks [ 'pre_del' ] = news.admin._subcat_pre_del;


	var p = '<div class ="glob-action adm-man-ico am_bin" title="Elimina Selezionati" onclick="AdminManager.del_all_item(\'%(_am_name)s\', true )"></div>';
	news.admin._am_sub_category.templates [ 'glob_delete' ] = p

	news.admin._am_sub_category.templates [ 'module_single_action' ] = news.templates [ 'module_single_action' ];
	
};

news.admin._subcat_pre_del = function ( am )
{
	var ids = am.get_selected ();
	if ( ids == -1 ) return true; 
	ids = "|".join ( ids )
	news.admin.del_category ( ids, true  )	
	return false;
};

news.admin._am_sub_category_filter_form = function ( dest_div )
{

        var f = new liwe.form.instance ( "sub_category_list_filter" );
        f.hidden ( "id_parent" , news.admin._cur_id_parent );
        f.set ( dest_div );
};


news.admin._rwman_sub_category = function ( ds, row )
{
        row [ '_id' ] = row [ 'id' ];
};

// }}}
// {{{ SubCategory SHOW FORM ADD EDIT

news.admin.show_sub_category = function ( id_category )
{
	
	var v = { action : 'news.ajax.get_categ', id_categ : id_category };
	news.ajax ( v , function ( data )
        {
		news.admin._cur_id_parent_name = data [ 'categ' ] [ 'text' ];
		$( 'title-work' , 'Lista Sotto Categorie di - [ ' + news.admin._cur_id_parent_name + ' ]' );
		news.admin._cur_id_parent = id_category ;
		news.admin._am_sub_category.show_list ( 'category_workspace' );
	});	
	
};

news.admin.add_sub_category = function ()
{
	$( 'title-work' , 'Nuova Sotto Categoria di- [ ' + news.admin._cur_id_parent_name + ' ]' );
	news.admin._sub_category_form( function ()
	{
		var f = liwe.form.get ( 'sub_category_add' );

		news.admin._cat_params = {
			'color' : '#000000',
			'ico' : '',
			'visible' : 0
		};
		news.admin._set_add_info ( f );
	});
}

news.admin.edit_sub_category = function ( id_category )
{
	$( 'title-work' , 'Modifica Sotto Categoria di - [ ' + news.admin._cur_id_parent_name + ' ]' );
	news.admin._sub_category_form();
	var v = { action : 'news.ajax.get_categ', id_categ : id_category };
	news.ajax ( v , function ( data )
        {

                var f = liwe.form.get ( 'sub_category_add' );
                data [ 'categ' ].iterate ( function ( val, k )
                {
                        f.set_value ( k, val );
                });
		f.set_value ( 'id_node', id_category );
		news.admin._set_add_info ( f, data [ 'categ' ] );
        });
};


news.admin._sub_category_form = function ( cback )
{
        var f = new liwe.form.instance ( 'sub_category_add' );

	liwe.AJAX.easy ( { action: 'news.admin.list_categs' }, function ( v ) {
		var categs = v [ 'categs' ];
		var opts = news.admin._create_sel_categ ( categs );

		f.hidden ( 'id' , '0' );
        	f.hidden ( 'id_node' , '0');
		f.select ( { label: 'Categoria', name: 'parent_id', value: news.admin._cur_id_parent , options: opts  } );
		f.text ( { 'name' : 'text', 'size' : 20, 'maxlength' : 50, 'mandatory' : true, 'label' : 'Sotto Categoria' } );
        	f.text ( { 'name' : 'color', 'size' : 10, 'maxlength' : 7, 'mandatory' : true, 'label' : 'Colore', 'onclick': 'ColorPicker.show(this)' } );
		f.checkbox ( { label: 'Visibile', name: 'visible', checked : false,  value : 1 } );
		f.label ( { 'label' : 'Immagine', value : "<div id='cat_img_ws'></div>" } );	
		f.button ( { value: 'Salva', "class": 'green', onclick : "news.admin._save_category( true )" });
		f.set ( 'category_workspace' );
		if ( cback ) cback();
	});

};




// }}}
/// }}}

news.admin.init = function ( dest_div )
{
	news.admin._init_admin ( dest_div );
};


/// {{{ KARMA OLD
news.admin._sel_categ_change = function ()
{
	var f = liwe.form.get ( "add_categ" );
	var el = f.get_element ( 'parent_id' );
	var id_node = el ? el.value : '';

	var txt = f.get_element ( 'text' );
	var id = f.get_element ( 'id_node' ).value;

	if ( ! id ) txt.value = '';

	$ ( 'cnt_list_categs' ).innerHTML = '';
	liwe.AJAX.easy ( { action: 'news.admin.list_categs', 'id_node': id_node }, function ( v ) {
		var categs = v [ 'categs' ];
		var t, l = categs.length;
		var s = [];

		for ( t = 0; t < l; t ++ )
		{
			var c = categs [ t ];

			s.push ( String.formatDict ( '<li><span class="admin_categ_row">%(text)s</span></li>', c ) )
		}

		if ( s.length > 0 )
			$ ( 'cnt_list_categs' ).innerHTML = "<ul>" + "".join ( s ) + "</ul>";
	} );

};
news.admin._create_categs = function ( cback )
{

	liwe.AJAX.easy ( { action: 'news.admin.list_categs' }, function ( v ) {
		var categs = v [ 'categs' ];
		var opts = [];

		function _categs2sel ( categs, prefix )
		{
			var t, l = categs.length;
			for ( t = 0; t < l; t ++ )
			{
				var c = categs [ t ];

				if ( c.get ( 'nodes' ) )
				{
					opts.push ( { value: c.id, label: c.text } );
					_categs2sel ( c.get ( 'nodes' ),  prefix + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" );
				}
				else opts.push ( { value: c.id, label: prefix + c.text } );
			}
		}

		opts.push ( { value: '', label: '' } );
		_categs2sel ( categs, "" );

		news.admin._categs = opts;

		if ( cback ) cback ();
	} );
};


news.admin._create_add_categ_frm = function ( dest, sottocat, dct )
{
	var f = new liwe.form.instance ( "add_categ" );
	if ( ! dct ) dct = {};

	liwe.AJAX.easy ( { action: 'news.admin.list_categs' }, function ( v ) {
		var categs = v [ 'categs' ];

		var id = dct.get ( 'id', 0 );

		var opts = news.admin._create_sel_categ ( categs );

		var msg = id ? 'Modifica' : 'Nuova';

		if ( sottocat )
		{
			f.select ( { label: 'Categorie', name: 'parent_id', value: dct.get ( 'id_parent', '' ), options: opts, onchange: "news.admin._sel_categ_change(this)" } );
			f.workspace ( { name: "cnt_list_categs" } );
			msg += ' sotto categoria';
		}
		else msg += ' categoria';

		f.hidden ( 'id_node', id );

		f.text ( { label: msg, name: 'text', mandatory: true, value: dct.get ( 'text', '' )  } );
		f.button ( { name: 'btn_save', "class": 'green', value: 'Salva', onclick: "news.admin._create_add_categ_frm_save(" + sottocat + ")"  } );

		f.set ( dest );
	} );
};

news.admin._create_add_categ_frm_save = function ( sottocat )
{
	var f = liwe.form.get ( "add_categ" );
	if ( ! f.check () )
	{
		alert ( 'Inserire tutti i valori' );
		return;
	}

	var dct = f.get_values ();

	dct [ 'action' ] = "news.admin.set_categ";

	liwe.AJAX.easy ( dct, function ( v ) {
		if ( news.admin.cbacks [ 'set-categ' ] ) news.admin.cbacks [ 'set-categ' ] ();
		else if ( sottocat ) news.admin._sel_categ_change ();

		news.admin._categs = null;
	} );
};

news.admin.add_sottocateg = function ( dest )
{
	news.admin._create_add_categ_frm ( dest, true );
};

news.admin._create_sel_categ = function ( v )
{
	var t, l = v.length;

	var res = [ { 'label': '', 'value': '' } ];

	for ( t = 0; t < l; t ++ )
	{
		var c = v [ t ];

		res.push ( { 'label': c.text, 'value': c.id } );
	}

	return res;
};



news.admin.list_categs = function ( dest, cback )
{
	if ( ! dest ) dest = 'block_main';

	$( dest, '<div id="cnt_list_categs"></div>' );

	liwe.AJAX.easy ( { action: 'news.admin.list_categs' }, function ( v ) {
		var categs = v [ 'categs' ];
		var s = [];

		function _render_nodes ( categs, id_node )
		{
			var t, l = categs.length;
			for ( t = 0; t < l; t ++ )
			{
				var c = categs [ t ];

				s.push ( String.formatDict ( '<li><a href="javascript:news.admin.set_categ(%(id)s,\'' + dest + '\')">' +
						'<span class="admin_categ_row">%(text)s</span></a></li>', c ) );


				if ( c.get ( 'nodes' ) )
				{
					s.push ( "<ul>" );
					_render_nodes ( c.get ( 'nodes' ), c [ 'id' ] );
					s.push ( "</ul>" );
					//s.push ( "</ul>" );
				}
				//else
				//	s.push ( String.formatDict ( '<li><a href="javascript:news.admin.set_categ(%(id)s,\'' + dest + '\')">' +
				//		'<span class="admin_categ_row">%(text)s</span></a></li>', c ) );
			}
		}

		s.push ( "<ul>" );
		_render_nodes ( categs );
		s.push ( "</ul>" );

		if ( s.length > 0 )
			$ ( 'cnt_list_categs' ).innerHTML = "".join ( s );

		cback && cback ();
	} );
};

news.admin.set_categ = function ( id, dest )
{
	news.admin.cbacks [ 'set-categ' ] = function () {
		news.admin.list_categs ( dest, function () {
			liwe.lightbox.close ();
		} );
	};

	liwe.AJAX.easy ( { action: 'news.ajax.get_categ', id_categ: id }, function ( v ) {
		var c = v [ 'categ' ];

		liwe.lightbox.fade = false;
		liwe.lightbox.easy ( "cnt_edit_frm_categ", "Modifica Categoria", 400, 400 );

		news.admin._create_add_categ_frm ( "cnt_edit_frm_categ", c [ 'id_parent' ], c );
	} );
};



// Nessuna chiamata nel codice
news.admin._format_list = function ( rows )
{
	var t, l = rows.length;
	var s = '';
	var templ = news.templates [ 'table_row' ];
	var r;
	
	for ( t = 0; t < l; t ++ )
	{
		r = rows [ t ];
		r [ '_actions' ] = '';
		//TODO: verificare se possiede i permessi necessari lato client

		r [ '_actions' ]  = String.formatDict ( news.templates [ 'del_news' ], r );
		r [ '_actions' ] += ' - ' + String.formatDict ( news.templates [ 'edit_news' ], r );


		s += String.formatDict ( templ, r );
	}

	if ( l > 0 ) s = news.templates [ 'table_start' ] + s + news.templates [ 'table_end' ];

	return s;
};
// }}}
